"""
修复refresh端点的详细日志版本
"""
from datetime import datetime, timedelta
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.orm import Session

from database import get_db, get_db_for_refresh
from auth import AuthHandler
from models import User, RefreshToken, LoginLog, Wallet
from schemas import Token, LoginRequest, RegisterRequest, RefreshTokenRequest, BaseResponse, UserResponse, AuthResponse

router = APIRouter()

def revoke_refresh_token_fixed(db: Session, token: str):
    """撤销刷新令牌 - 修复版本，不进行commit"""
    print(f"开始撤销令牌: {token[:50]}...")
    refresh_token = db.query(RefreshToken).filter(RefreshToken.token == token).first()
    if refresh_token:
        refresh_token.is_revoked = True
        print(f"✅ 标记令牌为已撤销")
    else:
        print(f"❌ 未找到要撤销的令牌")
    return refresh_token

def create_refresh_token_record_fixed(db: Session, user_id: int, token: str, expires_at: datetime):
    """创建刷新令牌记录 - 修复版本，不进行commit"""
    print(f"开始创建新令牌记录，用户ID: {user_id}")
    refresh_token = RefreshToken(
        user_id=user_id,
        token=token,
        expires_at=expires_at
    )
    db.add(refresh_token)
    print(f"✅ 已添加新令牌记录到会话")
    return refresh_token

@router.post("/refresh-v2", response_model=Token)
async def refresh_token_v2(
    refresh_data: RefreshTokenRequest,
    db: Session = Depends(get_db_for_refresh)
):
    """刷新访问令牌 - 修复版本"""
    print("=== refresh端点开始执行 ===")
    try:
        print(f"1. 验证刷新令牌")
        # 验证刷新令牌
        payload = AuthHandler.verify_token(refresh_data.refresh_token)
        username: str = payload.get("sub")
        token_type: str = payload.get("type")
        
        print(f"   令牌解析结果: 用户名={username}, 类型={token_type}")
        
        if username is None or token_type != "refresh":
            print(f"   ❌ 令牌验证失败: username={username}, token_type={token_type}")
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="无效的刷新令牌"
            )
        
        print(f"   ✅ 令牌验证成功")
        
        print(f"2. 检查数据库中的令牌记录")
        # 检查令牌是否被撤销
        refresh_token_record = db.query(RefreshToken).filter(
            RefreshToken.token == refresh_data.refresh_token,
            RefreshToken.is_revoked == False
        ).first()
        
        if not refresh_token_record:
            print(f"   ❌ 数据库中未找到有效的refresh token记录")
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="令牌已失效"
            )
        
        print(f"   ✅ 找到refresh token记录，用户ID: {refresh_token_record.user_id}")
        
        print(f"3. 获取用户信息")
        # 获取用户
        user = db.query(User).filter(User.username == username).first()
        if not user:
            print(f"   ❌ 未找到用户: {username}")
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="用户不存在"
            )
        
        print(f"   ✅ 找到用户: {user.id}, {user.username}")
        
        print(f"4. 创建新令牌")
        # 创建新的访问令牌
        access_token_expires = timedelta(minutes=60)
        access_token = AuthHandler.create_access_token(
            data={"sub": user.username}, expires_delta=access_token_expires
        )
        
        # 创建新的刷新令牌
        refresh_token_expires = timedelta(days=7)
        new_refresh_token = AuthHandler.create_refresh_token(
            data={"sub": user.username}, expires_delta=refresh_token_expires
        )
        
        print(f"   ✅ 令牌创建成功")
        
        print(f"5. 执行数据库操作")
        try:
            # 撤销旧令牌，保存新令牌 - 使用修复版本
            revoke_refresh_token_fixed(db, refresh_data.refresh_token)
            create_refresh_token_record_fixed(
                db, user.id, new_refresh_token,
                datetime.utcnow() + refresh_token_expires
            )
            
            print(f"6. 提交事务")
            db.commit()  # 手动提交事务
            print(f"   ✅ 事务提交成功")
            
        except Exception as db_error:
            print(f"   ❌ 数据库操作失败: {db_error}")
            db.rollback()  # 数据库操作失败时回滚
            import traceback
            traceback.print_exc()
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail=f"数据库操作失败: {str(db_error)}"
            )
        
        print(f"=== refresh端点执行成功 ===")
        return Token(
            access_token=access_token,
            expires_in=3600,
            refresh_token=new_refresh_token
        )
        
    except HTTPException:
        print(f"=== HTTPException: {e} ===")
        raise
    except Exception as e:
        print(f"=== refresh端点异常: {e} ===")
        import traceback
        traceback.print_exc()
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="令牌刷新失败"
        )